package com.yc.backstage.security.handler;

import cn.hutool.json.JSONUtil;
import com.yc.common.res.ResultClass;
import com.yc.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Classname LoginSuccessHandler
 * @Description 认证成功得回调函数 AuthenticationSuccessHandler：认证失败控制器
 * @Version 1.0.0
 * @Date 2022/7/26 14:24
 * @Created by Mikechen
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 生成JWT，并放置到请求头中
        String jwt = JwtUtils.createToken(authentication.getName());
        response.setHeader(JwtUtils.getHeader(), jwt);
        ResultClass result = ResultClass.success("SuccessLogin");
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
